package com.fzd.code.account.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fzd.code.account.LdapConfig;
import com.fzd.code.account.orm.model.Account;
import com.fzd.code.account.service.IAccountService;
import com.fzd.code.account.service.IAuthService;
import com.fzd.code.ldap.LdapUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("common-ldap-service")
@Slf4j
public class LdapAuthServiceImpl implements IAuthService {

    @Autowired
    private IAccountService accountService;

    @Autowired
    private LdapConfig ldapConfig;

    @Override
    public Account login(Account account) throws Exception {
        com.fzd.code.ldap.Account ldapAccount = new com.fzd.code.ldap.Account();
        ldapAccount.setAccountId(account.getAccountId());
        ldapAccount.setPassword(account.getPassword());
        LdapUtil ldapUtil = new LdapUtil();
        ldapUtil.setLdapConfig(ldapConfig);
        ldapUtil.login(ldapAccount);

        Account accountIdWhere = new Account();
        accountIdWhere.setAccountId(account.getAccountId());
        Account loginedAccount=this.accountService.selectOne(new EntityWrapper<>(accountIdWhere));
        if(loginedAccount==null){
            loginedAccount=new Account();
            loginedAccount.setAccountId(account.getAccountId());
            loginedAccount.setPassword(account.getPassword());
        }
        loginedAccount.setDepartment(ldapAccount.getDepartment());
        loginedAccount.setUserName(ldapAccount.getUserName());

        if(loginedAccount==null){
            this.accountService.insert(loginedAccount);
        }else{
            this.accountService.updateById(loginedAccount);
        }
        return loginedAccount;
    }

    @Override
    public void logout(String accountId) throws Exception {

    }
}
